/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * MeetRoomApplyController
 * 会议室预订申请
 * <p>
 * 修改纪录
 * 2020-10-26 版本：1.0 donghang 创建。
 *
 * @version 版本：1.0
 * @author 作者：donghang
 * 创建日期：2020-10-26
 */

package com.topscomm.meet.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.topscomm.base.BaseRemindTemplate;
import com.topscomm.pub.util.*;
import org.springframework.web.bind.annotation.*;

import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.meet.controller.auto.MeetRoomApplyControllerAuto;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;

/**
 * @author: donghang
 * @date: 2020-10-26
 * @description:会议室预订申请Controller
 * @modify:
 */
@RestController
@RequestMapping("meet/roomApply")
public class MeetRoomApplyController extends MeetRoomApplyControllerAuto implements IMeetRoomApplyController {
    /**
     * @param paraMap
     * @return
     * @author: donghang
     * @date: 2020-10-26
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_docno")) {
            String value = paraMap.get("qry_docno").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docno like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_begintimebegin")) {
            String value = paraMap.get("qry_begintimebegin").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and begintime >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_begintimeend")) {
            String value = paraMap.get("qry_begintimeend").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and begintime <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (username like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_usercode")) {
            String value = paraMap.get("qry_usercode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (usercode like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and deptcode like '{0}%'", value);
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and state={0}", value);
        }
        if (paraMap.containsKey("qry_where")) {
            String value = paraMap.get("qry_where").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and {0}", value);
        }
        SessionUserBean sessionUserBean = this.getUserBean();
        if (sessionUserBean.getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限throw
        {
            if (paraMap.containsKey("qry_isquery")
                    && ConvertUtil.convertToString(paraMap.get("qry_isquery")).equals("1")) {
                String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", sessionUserBean);
                if (!StringUtil.isEmpty(dataPession)) {
                    sql.appendSingle(" and {0} ", dataPession);
                } else {
                    sql.appendSingle(" and (usercode = '{0}')", this.getUserBean().getUser().getCode());
                }
            } else {
                sql.appendSingle(" and (usercode = '{0}')", this.getUserBean().getUser().getCode());
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @author: donghang
     * @date: 2020-10-26
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * @param dataMap
     * @param paraMap
     * @throws Exception
     * @description:
     * @author: donghang
     * @date: 2020年10月26日上午11:16:56
     * @modify:
     */
    @Override
    protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        super.beforeSubmit(dataMap, paraMap);
        if (ConvertUtil.convertToLong(dataMap.get("flowid")) <= 0) {
            throw new Exception("审批流程缺失，请选择审批流程");
        }
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交会议室预订申请单,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"),
                DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
        dataMap.put("maintitle", mailtitle.toString());
    }

    /**
     * @description: 添加额外的数据项
     * @author: chengengwei
     * @date: 2021-06-18
     * @modify:
     */
    @Override
    public void mainListExtraData(Map<String, Object> paraMap, Map<String, Object> mainListData) {
        // 获取会议配置
        List<Map<String, Object>> meetBoardRoomConfigList = datacodeCache.getCodeListMap("MeetBoardRoomConfig",
                "", "sortcode");
        String sourcelist = ConvertUtil.convertToString(mainListData.get("sourcelist"));
        StringBuffer dispsourcelist = new StringBuffer();
        // 转换为name拼接的dispsourcelist
        if (!StringUtil.isEmpty(sourcelist)) {
            String[] codes = sourcelist.split(",");
            for (String code : codes) {
                for (Map<String, Object> map : meetBoardRoomConfigList) {
                    if (map.get("code").equals(code)) {
                        dispsourcelist.append(map.get("name") + ",");
                        break;
                    }
                }
            }
            mainListData.put("dispsourcelist", dispsourcelist.substring(0, dispsourcelist.length() - 1));
        }
    }


    /**
     * @param paraMap
     * @return
     * @author chengengwei
     * @date 2021-04-10
     * @description 重写取消审批，使普通用户也能取消审批
     */
    @DeleteMapping(value = "/delApproval")
    public ResponseResult<Object> delApproval(@RequestBody(required = false) Map<String, Object> paraMap) {
        Map<String, Object> dataMap = paraMap;
        String id = ConvertUtil.convertToString(dataMap.get("id"));
        this.service.executeDelApprove(id, this.getUserBean());
        return ResponseResult.ok("取消审批成功");
    }

    /**
     * @param
     * @return
     * @throws
     * @description: 会议室
     * @author xinfushuo
     * @date 2022/6/7
     * @modify
     */
    @PostMapping(value = "/beforeApply")
    public ResponseResult<Object> beforeRoomApply(@RequestBody Map<String, Object> paraMap) {
        BaseUtil.decodeSecureMap(paraMap);
        Map<String, Object> resultMap = new HashMap<>();
        Date begin = ConvertUtil.convertToDate(paraMap.get("begintime"));
        Date end = ConvertUtil.convertToDate(paraMap.get("endtime"));
        String roomId = ConvertUtil.convertToString(paraMap.get("roomid"));
        boolean meetRoomCollision = this.service.checkTimeCollison(begin, end, roomId);
        resultMap.put("NeedRemindCollison", meetRoomCollision);
        String msg;
        if (meetRoomCollision) {
            msg = BaseRemindTemplate.AppRemindTemplate.MeetRoomCollisionMessageTemplate;
        } else {
            msg = "";
        }
        return ResponseResult.ok(msg, resultMap);
    }


    /**
     * @param paraMap
     * @return
     * @description:审批
     * @author: zhanglongfei
     * @date: 2020年3月20日下午5:36:36
     * @modify:
     */
    @PutMapping(value = "/approval")
    public ResponseResult<Object> approval(@RequestBody(required = false) Map<String, Object> paraMap) {
        // 执行审批操作
        String approvalOpinion = paraMap.get("approvalopinion").toString();
        String approvalType = paraMap.get("approvaltype").toString();
        String nodeInsId = paraMap.get("nodeinsid").toString();
        String backNodeId = ConvertUtil.convertToString(paraMap.get("backnodeid"));
        long nextUserId = 0;
        if (paraMap.containsKey("nextuserid") && !StringUtil.isEmpty(paraMap.get("nextuserid").toString())) {
            nextUserId = Long.parseLong(paraMap.get("nextuserid").toString());
        }
        this.service.executeApprove(nodeInsId, new Date(), approvalOpinion, approvalType, backNodeId,
                this.getUserBean(), nextUserId);
        return ResponseResult.ok("操作成功");
    }

}
